package beans;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import oracle.adf.view.rich.component.rich.RichPopup;
import oracle.adf.view.rich.component.rich.input.RichInputText;
import oracle.adf.view.rich.component.rich.layout.RichPanelSplitter;

import org.apache.myfaces.trinidad.model.UploadedFile;
import org.apache.myfaces.trinidad.render.ExtendedRenderKitService;
import org.apache.myfaces.trinidad.util.Service;


public class JavaEmailBB {

    private RichInputText toBinding;
    private RichInputText subjectBinding;
    private RichInputText messageBinding;
    private RichInputText emailIdBinding;
    private RichInputText passwordBinding;
    private String emailId;
    private String pwd;
    private String file_name;

    private RichInputText showPopUpBind;
    private RichPopup loginPopUpBind;
    private boolean attachFile = false;
    private String uiPage = "/pageMail.jsf";
    private RichPanelSplitter panelSplitter;
    String accountSoc = "gmail";
    Properties emailProperties;
    Session mailSession;
    MimeMessage emailMessage;
    String toWhom;
    String messagae;
    String subject;

    private javax.mail.Store store;

    public JavaEmailBB() {
    }
    

    public void sendMailButton(ActionEvent actionEvent) throws AddressException, MessagingException {
        if (toBinding.getValue() == null || subjectBinding.getValue() == null || messageBinding.getValue() == null) {
            FacesMessage msg = new FacesMessage("Please Enter The Fields both");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
        }
        setMailServerProperties();
        createEmailMessage();
        sendEmail();
    }

    public void setMailServerProperties() {
        if (accountSoc.equals("gmail")) {
            String emailPort = "587"; //gmail's smtp port
            emailProperties = System.getProperties();
            emailProperties.put("mail.smtp.port", emailPort);
            emailProperties.put("mail.smtp.auth", "true");
            emailProperties.put("mail.smtp.starttls.enable", "true");
        }
    }

    public void createEmailMessage() throws AddressException, MessagingException {
        toWhom = toBinding.getValue().toString(); // Value From page(Reciepient)
        subject = subjectBinding.getValue().toString(); // Value from page(Subject)
        messagae = messageBinding.getValue().toString(); // Value from page(Message/Mail)
        String[] toEmails = { toWhom };
        String emailSubject = subject;
        String emailBody = messagae;
        System.out.println("to---->" + toEmails + "subject is-->" + emailSubject + "body is--->" + emailBody);
        mailSession = Session.getDefaultInstance(emailProperties, null);

        if (!"gmail".equals(accountSoc)) {
            properties = System.getProperties();           
            mailSession = Session.getInstance(properties, null);
        }
        emailMessage = new MimeMessage(mailSession);
        for (int i = 0; i < toEmails.length; i++) {
            emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmails[i]));
        }

        emailMessage.setSubject(emailSubject);

        //1) create MimeBodyPart object and set your message content
        BodyPart messageBodyPart1 = new MimeBodyPart();
        messageBodyPart1.setText(emailBody);

        //2) create new MimeBodyPart object and set DataHandler object to this object
        MimeBodyPart messageBodyPart2 = new MimeBodyPart();

        String filename = "D://" + file_name; //change accordingly
        System.out.println("Exact path--->" + filename);
        DataSource source = new FileDataSource(filename);
        messageBodyPart2.setDataHandler(new DataHandler(source));
        messageBodyPart2.setFileName(filename);


        //5) create Multipart object and add MimeBodyPart objects to this object
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart1);
        multipart.addBodyPart(messageBodyPart2);

        //6) set the multiplart object to the message object
        emailMessage.setContent(multipart);

        // emailMessage.setContent(emailBody, "text/html");//for a html email
        //emailMessage.setText(emailBody);// for a text email

    }

    public void createEmailMessageWidtAtchmnt() throws AddressException, MessagingException {
        toWhom = toBinding.getValue().toString();
        subject = subjectBinding.getValue().toString();
        messagae = messageBinding.getValue().toString();
        String[] toEmails = { toWhom };
        System.out.println("To whom is-->{" + toWhom + "} total contact is-->" + toEmails.length);
        String emailSubject = subject;
        String emailBody = messagae;
        System.out.println("to---->" + toEmails + "subject is-->" + emailSubject + "body is--->" + emailBody);
        mailSession = Session.getDefaultInstance(emailProperties, null);
        emailMessage = new MimeMessage(mailSession);

        for (int i = 0; i < toEmails.length; i++) {
            emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmails[i]));
        }

        emailMessage.setSubject(emailSubject);

        //1) create MimeBodyPart object and set your message content
        BodyPart messageBodyPart1 = new MimeBodyPart();
        messageBodyPart1.setText(emailBody);

        emailMessage.setContent(emailBody, "text/html"); //for a html email


    }

    public void sendEmail() {
        String emailHost = "";
        if (accountSoc.equals("gmail")) {
            emailHost = "smtp.gmail.com";
        } else {
            emailHost = "smtp.mail.yahoo.com";
        }

        String fromUser = emailId; //just the id alone without @gmail.com
        String fromUserEmailPassword = pwd;
        Transport transport = null;
        try {
            if("gmail".equals(accountSoc)){
            transport = mailSession.getTransport("smtp");
            }else{
                    java.util.Properties properties=System.getProperties();
                    mailSession= Session.getInstance(properties,null);
                    transport= mailSession.getTransport("smtps");
                }
        } catch (NoSuchProviderException e) {
            System.out.println("No such Provider Exception");
        }
       try {
            if (accountSoc.equals("gmail")) {
                transport.connect(emailHost, fromUser, fromUserEmailPassword);
            } else { emailMessage.setFrom(new InternetAddress("emiliamatei11@yahoo.com"));                              
                transport.connect(emailHost, 465  , fromUser+"@yahoo.com", pwd);
            }
            transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
            transport.close();
            StringBuilder msgEmail = new StringBuilder("<html><body><b>Email Sent</b></body></html>");
            FacesMessage msg = new FacesMessage(msgEmail.toString());
            msg.setSeverity(FacesMessage.SEVERITY_INFO);
            FacesContext.getCurrentInstance().addMessage("No Network Error !", msg);
            System.out.println("Email sent successfully.");
            

        } catch (MessagingException e) {
            System.out.println("somthing went wrong-->Messaging Exception");
            System.out.println(e);
            StringBuilder msgEmail = new StringBuilder("<html><body><b>Something went wrong !</b>");
            msgEmail.append("<p><b>please provide correct parameters</b></p>");
            msgEmail.append("</body></html>");
            FacesMessage msg = new FacesMessage(msgEmail.toString());
            msg.setSeverity(FacesMessage.SEVERITY_WARN);
            FacesContext.getCurrentInstance().addMessage("No Network Error !", msg);

        }

    }
    


    public void uploadedFileAttachmentVCE(ValueChangeEvent valueChangeEvent) {
        UploadedFile file = (UploadedFile)valueChangeEvent.getNewValue();
        file_name = file.getFilename();
    }

    public void setToBinding(RichInputText toBind) {
        this.toBinding = toBind;
    }

    public RichInputText getToBinding() {
        return toBinding;
    }

    public void setSubjectBinding(RichInputText subjectBind) {
        this.subjectBinding = subjectBind;
    }

    public RichInputText getSubjectBinding() {
        return subjectBinding;
    }

    public void setMessageBinding(RichInputText messageBind) {
        this.messageBinding = messageBind;
    }

    public RichInputText getMessageBinding() {
        return messageBinding;
    }

    public void setEmailIdBinding(RichInputText emailIdBind) {
        this.emailIdBinding = emailIdBind;
    }

    public RichInputText getEmailIdBinding() {
        return emailIdBinding;
    }

    public void setPasswordBinding(RichInputText passwordBind) {
        this.passwordBinding = passwordBind;
    }

    public RichInputText getPasswordBinding() {
        return passwordBinding;
    }

    public void signInButton(ActionEvent actionEvent) {

    }

    public void logOutlink(ActionEvent actionEvent) {
        setEmailId("");
        setPwd("");
        toBinding.setValue("");
        subjectBinding.setValue("");
        messageBinding.setValue("");
        this.attachFile = false;
    }

    public void showPopup(RichPopup popup, boolean visible) {
        try {
            FacesContext context = FacesContext.getCurrentInstance();
            if (context != null && popup != null) {
                String popupId = popup.getClientId(context);
                if (popupId != null) {
                    StringBuilder script = new StringBuilder();
                    script.append("var popup = AdfPage.PAGE.findComponent('").append(popupId).append("'); ");
                    if (visible) {
                        script.append("if (!popup.isPopupVisible()) { ").append("popup.show();}");

                    } else {
                        script.append("if (popup.isPopupVisible()) { ").append("popup.hide();}");
                    }
                    ExtendedRenderKitService erks =
                        Service.getService(context.getRenderKit(), ExtendedRenderKitService.class);
                    erks.addScript(context, script.toString());
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void setEmailId(String emailId) {
        this.emailId = emailId;
    }

    public String getEmailId() {
        return emailId;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public String getPwd() {
        return pwd;
    }


    public void setShowPopUpBind(RichInputText showPopUpBind) {
        this.showPopUpBind = showPopUpBind;
    }

    public RichInputText getShowPopUpBind() {

        return showPopUpBind;
    }

    public void setLoginPopUpBind(RichPopup loginPopUpBind) {
        this.loginPopUpBind = loginPopUpBind;
    }

    public RichPopup getLoginPopUpBind() {
        return loginPopUpBind;
    }

    public void attachFilesLink(ActionEvent actionEvent) {
        this.attachFile = true;
    }

    public void sendWithoutAttachement(ActionEvent actionEvent) throws AddressException, MessagingException {
        if (toBinding.getValue() == null || subjectBinding.getValue() == null || messageBinding.getValue() == null) {
            FacesMessage msg = new FacesMessage("Please Enter The Fields both");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
        }
        setMailServerProperties();
        createEmailMessageWidtAtchmnt();
        sendEmail();
    }

    public void setAttachFile(boolean attachFile) {
        this.attachFile = attachFile;
    }

    public boolean isAttachFile() {
        return attachFile;
    }


    private java.util.Properties properties;

    public String signInAction() {
        if (emailIdBinding.getValue() == null || passwordBinding.getValue() == null) {
            FacesMessage msg = new FacesMessage("Please Enter Email and Password both");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return null;
        } else {
            emailId = emailIdBinding.getValue().toString();
            pwd = passwordBinding.getValue().toString();
            if (!accountSoc.equals("gmail")) {
                properties = System.getProperties();
                mailSession = Session.getInstance(properties, null);
                try {
                    store = mailSession.getStore("imaps");
                } catch (NoSuchProviderException e) {
                    System.out.println("Eroare1" + e);
                }
                try {
                    store.connect("imap.mail.yahoo.com", 993, emailId, pwd);
                } catch (MessagingException e) {
                    System.out.println("Eroare2" + e);
                }
            }
            return "";
        }
    }

    public void setUiPage(String uiPage) {
        this.uiPage = uiPage;
    }

    public String getUiPage() {
        return uiPage;
    }


    public void setPanelSplitter(RichPanelSplitter panelSplitter) {
        this.panelSplitter = panelSplitter;
    }

    public RichPanelSplitter getPanelSplitter() {
        return panelSplitter;
    }

    public void setAccountSoc(String accountSoc) {
        this.accountSoc = accountSoc;
    }

    public String getAccountSoc() {
        return accountSoc;
    }


}
